<template>
  <el-dialog
      v-model="visible"
      :title="dialogTitle"
      width="640px"
      class="dialog"
      destroy-on-close
      @closed="handleClosed"
  >
    <el-form
        :model="formData"
        label-width="100px"
        ref="formRef"
        :rules="rules"
        class="form"
    >
      <el-row :gutter="20">

        <!-- 菜单类型 -->
        <el-col :span="24">
          <el-form-item label="菜单类型" prop="menuType" required>
            <el-select v-model="formData.menuType" placeholder="请选择菜单类型">
              <el-option
                  v-for="item in menuTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 菜单编码 -->
        <el-col :span="24">
          <el-form-item label="菜单编码" prop="menuCode" required>
            <el-input v-model="formData.menuCode" placeholder="请输入菜单编码"/>
          </el-form-item>
        </el-col>

        <!-- 菜单名称 -->
        <el-col :span="24">
          <el-form-item label="菜单名称" prop="menuName" required>
            <el-input v-model="formData.menuName" placeholder="请输入菜单名称"/>
          </el-form-item>
        </el-col>

        <!-- 菜单地址（仅页面类型时显示） -->
        <el-col :span="24" v-if="formData.menuType === 'C'">
          <el-form-item label="菜单地址" prop="menuUrl">
            <el-input v-model="formData.menuUrl" placeholder="请输入菜单地址"/>
          </el-form-item>
        </el-col>

        <!-- 排序 -->
        <el-col :span="24">
          <el-form-item label="排序" prop="menuOrder">
            <el-input-number v-model="formData.menuOrder" :min="0" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false" round>取 消</el-button>
        <el-button type="primary" @click="submitForm" round>提 交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {MenuItem} from "@/views/menu/menu"

const emit = defineEmits(['submit'])

const formRef = ref<FormInstance>()

// 表单数据
const formData = ref<MenuItem>({
  menuId: null,
  menuCode: "",
  menuName: "",
  menuType: "",
  menuPreId: null,
  menuUrl: null,
  menuOrder: 0
})

// 校验规则
const rules: FormRules = {
  menuType: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  menuCode: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
  menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  menuUrl: [
    {
      required: true,
      message: '请输入菜单地址',
      trigger: 'blur',
      validator: (_rule, value, callback) => {
        if (formData.value.menuType === 'C' && !value) {
          callback(new Error('请输入菜单地址'))
        } else {
          callback()
        }
      }
    }
  ]
}

const visible = ref(false)
const dialogTitle = ref('')
const preType = ref('')

// 计算可选的菜单类型
const menuTypeOptions = computed(() => {
  if (preType.value === 'M') {
    return [
      {label: "目录", value: "M"},
      {label: "页面", value: "C"}
    ]
  } else if (preType.value === 'C') {
    return [
      {label: "按钮", value: "B"}
    ]
  }
  return []
})

// 打开弹窗
const openDialog = (menuType: string, menuPid?: number, rowData?: MenuItem) => {
  preType.value = menuType
  if (rowData && rowData.menuId) {
    dialogTitle.value = '修改菜单'
    formData.value = {...rowData}
  } else {
    dialogTitle.value = '新增菜单'
    Object.assign(formData.value, {
      menuId: null,
      menuCode: "",
      menuName: "",
      menuType: "",
      menuPreId: menuPid ?? null,
      menuUrl: null,
      menuOrder: 0
    })
  }
  visible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    emit('submit', formData.value)
    visible.value = false
  } catch (error) {
    console.log('Form validation failed')
  }
}

// 关闭时清理表单
const handleClosed = () => {
  formRef.value?.resetFields()
}

defineExpose({openDialog})
</script>

<style scoped>
.dialog {
  border-radius: 12px;
}

.form {
  padding: 10px 10px 0 0;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style>